//
//  ClubGameStrategyViewController.swift
//  77Club
//
//  Created by Apple on 2024/11/5.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser

private let headerID    = "ClubSquareDatailHeaderView"

class ClubGameStrategyViewController: ClubBaseViewController {

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameStrategyTopCell.self,ClubForumEquipCell.self,ClubForumImageTextCell.self)
        tableView.register(ClubSquareDatailHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100.0.Scale
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    
    var gameModel: ClubGameDetailModel?
    private var model: ClubGameCommunityModel?
    private var bolckData: [ClubStrategyBlockModel]?
    private var pageIndex = 1
    
    var communityId: String = ""{
        didSet{
            loadData()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(toPostDetailVC), name: .forumToGameDetailVC, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            tableView
        }
        
        tableView.fillContainer()
        
        
    }
        
    @objc private func toPostDetailVC(noti: Notification){
        
        if let newsID = noti.userInfo?["infoID"] as? String {
            self.toDetailVC(newId: newsID, uid: "0")
        }
    }
    
    private func toDetailVC(newId: String, uid: String){
        
        if uid == "0" {
            let detailVC = ClubForumDetailViewController()
            detailVC.newId = newId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else{
            let detailVC = ClubGameForumDetailViewController()
            detailVC.postID = newId
            detailVC.pid = self.communityId
            detailVC.gameModel = self.gameModel
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubGameStrategyViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {

       return (self.bolckData?.count ?? 0) + 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameStrategyTopCell", for: indexPath) as! ClubGameStrategyTopCell
            cell.models = model?.news
            cell.jumpToDetail = { newsId, uid in
                self.toDetailVC(newId: newsId, uid: uid)
            }
            return cell
        }else{
            //攻略
            let model = bolckData?[indexPath.section - 1]
            if model?.image == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumImageTextCell", for: indexPath) as! ClubForumImageTextCell
                cell.news = model?.news
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubForumEquipCell", for: indexPath) as! ClubForumEquipCell
                cell.news = model?.news
                return cell
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {
            return nil
        }
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubSquareDatailHeaderView
        header.titleString = self.bolckData?[section - 1].name
        header.isWhite = true
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

        if section == 0 {
            return 0
        }
        return 44.0.Scale
    }
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}


//MARK: data
extension ClubGameStrategyViewController {
    
    
    private func loadData(){
        
        ToastUtil.show()
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameStrategyList")
        
        netGroup.enter()
        workingQueue.async {
            //攻略
            Task {
                let res = await self.network.requestMore(.strategyInfo(communityID: self.communityId, page: 1),type: ClubStrategyModel.self)
                if res.isSuccess, let model = res.model {
                    self.bolckData = model.blocks
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            
            Task{
                let res = await self.network.request(.communityTop(communityID: self.communityId),type: ClubGameCommunityModel.self)
                if res.isSuccess, let model = res.model {
                    self.model = model
                    netGroup.leave()
                }
            }
        }
        
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                ToastUtil.dismiss()
                self.tableView.reloadData()
            }
        }
    }
}

extension ClubGameStrategyViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}


class ClubGameStrategyTopCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F7F8FA".toColor
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubSquareDetailTopItemCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 30.0.Scale
        tableView.layer.cornerRadius = 12.0.Scale
        tableView.layer.masksToBounds = true
        return tableView
    }()
    
    var jumpToDetail:((_:String, _ uid: String)->())?
    
    var models:[ClubGameCommunityNewsModel]? {
        didSet{
            guard let arr = models, arr.count > 0 else { return }
            if arr.count <= 3 {
                tableView.heightConstraint?.constant = Double(arr.count) * 30.0.Scale
            }else{
                tableView.heightConstraint?.constant = 90.0.Scale
            }
            tableView.reloadData()
        }
    }
    
    var isWhite = false{
        didSet{
            if isWhite{
                tableView.backgroundColor = .white
            }else{
                tableView.backgroundColor = "#F7F8FA".toColor
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initUI()
    }
    
    func initUI() -> Void {
        
        selectionStyle = UITableViewCell.SelectionStyle.none
        backgroundColor = UIColor.clear
        
        contentView.subviews{
            tableView
        }

        tableView.leading(12.0.Scale).trailing(12.0.Scale).height(90.0.Scale).top(12.0.Scale).bottom(8.0.Scale)
    }
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return models?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareDetailTopItemCell", for: indexPath) as! ClubSquareDetailTopItemCell
        cell.model = models?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let md = models?[indexPath.row] else { return }
        jumpToDetail?(md.id,md.uid)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
